package org.sensation.server.file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.sensation.file.channel.SetupToWriteTempFile;
import org.sensation.server.file.transfer.SelectedKeyDispacheService;

public class SensationFileReceiveServer implements Runnable{
	private Selector selector;
	private DatagramChannel serverChannel;
	public int port = 5880;
	private InetSocketAddress serverInetSocketAddress;
	private SelectedKeyDispacheService selectedKeyDispacheService;
	private Logger logger = Logger.getLogger(SensationFileReceiveServer.class);
	
	public SensationFileReceiveServer(String targetFilePath, int targetFileSize) throws IOException{
		setupServerChannelData();
		setupServerChannelRegister();
		setupToWriteTempFile(targetFilePath, targetFileSize);
		
		this.selectedKeyDispacheService = new SelectedKeyDispacheService();
		logger.debug("SensationFileTransferServer constructor complete");
	}
	
	public void run(){
		logger.info("SensationFileTransferServer run");
		while(true){
			try {
				selector.select();
				Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
				selectedKeyDispacheService.dispatchService(keys);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void setupServerChannelData() throws IOException {
		serverInetSocketAddress = new InetSocketAddress(port);
		selector = Selector.open();
	}

	private void setupServerChannelRegister() throws IOException, SocketException,
			ClosedChannelException {
		serverChannel = DatagramChannel.open();
		serverChannel.socket().bind(serverInetSocketAddress);
		serverChannel.configureBlocking(false);
		serverChannel.register(selector, SelectionKey.OP_READ);
	}
	
	private void setupToWriteTempFile(String targetFilePath, int targetFileSize)
			throws FileNotFoundException, IOException {
		SetupToWriteTempFile tempFile = new SetupToWriteTempFile(targetFilePath, targetFileSize);
	}
}
